package com.suyang.syt.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Locale;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.support.RequestContextUtils;
import org.springframework.web.servlet.view.freemarker.FreeMarkerView;

import com.suyang.syt.context.BeanFactoryContext;

import freemarker.template.SimpleHash;
import freemarker.template.Template;
import freemarker.template.TemplateException;

@SuppressWarnings({ "rawtypes", "unchecked" })
public class MyFreeMarkerView extends FreeMarkerView {
	private static final String CONTEXT_PATH = "basePath";

	@Override
	protected void exposeHelpers(Map<String, Object> model, HttpServletRequest request) throws Exception {
		model.put(CONTEXT_PATH, request.getContextPath());
		super.exposeHelpers(model, request);
	}

	@Override
	protected void doRender(Map model, HttpServletRequest request, HttpServletResponse response) throws Exception {
		exposeModelAsRequestAttributes(model, request);
		SimpleHash fmModel = buildTemplateModel(model, request, response);

		Locale locale = RequestContextUtils.getLocale(request);
		/*
		 * 默认生成静态文件,若不想生成静态文件设置ModelAndView.addObject("STATIC_PAGE",false);
		 */
		if (Boolean.FALSE.equals(model.get("STATIC_PAGE"))) {
			processTemplate(getTemplate(locale), fmModel, response);
		} else {
			createHTML(getTemplate(locale), fmModel, request, response);

		}
	}

	public void createHTML(Template template, SimpleHash model, HttpServletRequest request, HttpServletResponse response) throws IOException, TemplateException, ServletException {
		// 站点根目录的绝对路径
		String basePath = BeanFactoryContext.getRealPath();
		String requestHTML = this.getRequestHTML(request);
		// 静态页面绝对路径
		String htmlPath = basePath + requestHTML;
		System.out.println("htmlPath : " + htmlPath);
		File htmlFile = new File(htmlPath);

		if (!htmlFile.getParentFile().exists()) {
			htmlFile.getParentFile().mkdirs();
		}
		/**
		 * 如果静态页面已经存在,就不再创建静态 页面.
		 */
		if (!htmlFile.exists()) {
			htmlFile.createNewFile();
			Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(htmlFile), "UTF-8"));
			// 处理模版
			template.process(model, out);
			out.flush();
			out.close();
		}
		/* 将请求转发到生成的html文件 */
		request.getRequestDispatcher(requestHTML).forward(request, response);
	}

	/**
	 * 计算要生成的静态文件相对路径.
	 */
	private String getRequestHTML(HttpServletRequest request) {

		// web应用名称,部署在ROOT目录时为空
		String contextPath = request.getContextPath();
		// web应用/目录/文件.do
		String requestURI = request.getRequestURI();
		// basePath里面已经有了web应用名称，所以直接把它replace掉，以免重复
		requestURI = requestURI.replaceFirst(contextPath, "");
		// 将请求改为.html,稍后将请求转发到此html文件
		if (requestURI.indexOf(".") <= 0) {
			requestURI += ".html";
		} else {
			requestURI = requestURI.substring(0, requestURI.indexOf(".")) + ".html";
		}
		return requestURI;
	}

}
